import sys
import os
import json
from PySide6.QtWidgets import (QApplication, QWidget, QDialog, QVBoxLayout, QHBoxLayout,
                               QLabel, QSlider, QPushButton, QColorDialog, QComboBox,
                               QCheckBox, QSpinBox, QTabWidget, QSizePolicy, QGroupBox,
                               QLineEdit, QMenu, QMessageBox, QFrame, QScrollArea,
                               QSystemTrayIcon, QGridLayout, QDoubleSpinBox, QListWidget)
from PySide6.QtCore import Qt, QPoint, QTimer, QSize, QRect, Signal, QPointF, QUrl
from PySide6.QtGui import (QPainter, QPen, QColor, QMouseEvent, QPalette,
                           QBrush, QCursor, QPixmap, QImage, QFont,
                           QAction, QPixmap, QRadialGradient, QBrush,
                           QDesktopServices, QConicalGradient, QIcon)

# 设置文件路径
SETTINGS_FILE = "D:\\crosshair_json\\crosshair_settings.json"
POSITION_FILE = "D:\\crosshair_json\\crosshair_position.json"
POSITION_HISTORY_FILE = "D:\\crosshair_json\\position_history.json"


def create_app_icon():
    """生成应用程序图标（64x64像素）"""
    size = 64
    pixmap = QPixmap(size, size)
    pixmap.fill(Qt.transparent)

    painter = QPainter(pixmap)
    painter.setRenderHint(QPainter.Antialiasing)

    # 绘制渐变背景
    gradient = QRadialGradient(size / 2, size / 2, size / 2)
    gradient.setColorAt(0, QColor(52, 152, 219, 200))
    gradient.setColorAt(1, QColor(155, 89, 182, 200))
    painter.setBrush(QBrush(gradient))
    painter.drawEllipse(0, 0, size, size)

    # 绘制十字准星
    arm_length = size * 0.35
    center = size / 2
    painter.setPen(QPen(Qt.white, size * 0.08, Qt.SolidLine, Qt.RoundCap))
    painter.drawLine(center - arm_length, center, center + arm_length, center)
    painter.drawLine(center, center - arm_length, center, center + arm_length)

    # 绘制中心点
    painter.setPen(Qt.NoPen)
    painter.setBrush(Qt.white)
    painter.drawEllipse(QPointF(center, center), size * 0.1, size * 0.1)

    painter.end()
    return pixmap


class CrosshairWidget(QWidget):
    """
    准星显示主窗口类，负责准星的绘制和基本功能实现
    """

    def __init__(self, settings=None):
        """
        初始化准星窗口

        参数:
            settings: 可选，如果提供则使用提供的设置，否则从文件加载
        """
        super().__init__()

        # 初始化状态变量
        self.locked = True  # 准星默认锁定，不能直接拖动
        self.dragging = False  # 是否正在拖动
        self.offset = QPoint()  # 拖动时的偏移量
        self.opacity = 1.0  # 窗口透明度
        self.last_mouse_pos = QPoint()  # 记录最后鼠标位置

        # 初始化系统托盘图标
        self.tray_icon = None
        self.init_system_tray()

        # 加载设置
        self.settings = self.load_settings() if settings is None else settings

        # 加载位置历史记录
        self.position_history = self.load_position_history()

        # 设置窗口属性
        self.setup_window_properties()

        # Windows平台特定优化
        if sys.platform == "win32":
            self.apply_windows_optimizations()
            self.hide_from_taskbar()

        # 加载窗口位置信息
        self.load_window_position()

        # 初始化自动隐藏计时器
        self.init_hide_timer()

    def setup_window_properties(self):
        """设置窗口基本属性"""
        self.setWindowFlags(
            Qt.FramelessWindowHint |  # 无边框
            Qt.WindowStaysOnTopHint |  # 始终置顶
            Qt.SubWindow |  # 子窗口
            Qt.BypassWindowManagerHint |  # 绕过窗口管理器
            Qt.WindowTransparentForInput  # 透明输入
        )
        self.setAttribute(Qt.WA_TranslucentBackground)  # 透明背景
        self.setAttribute(Qt.WA_NoSystemBackground, True)  # 无系统背景
        self.setAttribute(Qt.WA_ShowWithoutActivating)  # 不激活显示
        self.setAttribute(Qt.WA_TransparentForMouseEvents)  # 鼠标事件穿透
        self.setCursor(Qt.BlankCursor)  # 隐藏鼠标光标
        self.setMinimumSize(150, 150)  # 最小尺寸

    def init_hide_timer(self):
        """初始化自动隐藏计时器"""
        self.hide_timer = QTimer(self)
        self.hide_timer.timeout.connect(self.check_hide_condition)
        self.hide_timer.start(100)

    def init_system_tray(self):
        """初始化系统托盘图标和菜单"""
        if not QSystemTrayIcon.isSystemTrayAvailable():
            return

        # 创建托盘图标
        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(QIcon(self.create_tray_icon()))

        # 创建托盘菜单
        tray_menu = QMenu()

        # 添加菜单项
        settings_action = QAction("设置", self)
        settings_action.triggered.connect(self.show_settings)
        tray_menu.addAction(settings_action)

        center_action = QAction("居中", self)
        center_action.triggered.connect(self.center_window)
        tray_menu.addAction(center_action)

        tray_menu.addSeparator()

        exit_action = QAction("退出", self)
        exit_action.triggered.connect(self.quit_app)
        tray_menu.addAction(exit_action)

        # 设置菜单并显示
        self.tray_icon.setContextMenu(tray_menu)
        self.tray_icon.show()

        # 连接点击事件
        self.tray_icon.activated.connect(self.tray_icon_clicked)

    def create_tray_icon(self):
        """创建托盘图标图像"""
        pixmap = QPixmap(32, 32)
        pixmap.fill(Qt.transparent)

        painter = QPainter(pixmap)
        painter.setRenderHint(QPainter.Antialiasing)

        # 绘制准星图标
        color = QColor(255, 50, 50)
        painter.setPen(QPen(color, 2))

        center = QPointF(16, 16)
        size = 10

        # 绘制十字线
        painter.drawLine(center.x(), center.y() - size, center.x(), center.y() + size)
        painter.drawLine(center.x() - size, center.y(), center.x() + size, center.y())

        # 绘制中心点
        painter.setBrush(color)
        painter.drawEllipse(center, 3, 3)

        painter.end()
        return pixmap

    def tray_icon_clicked(self, reason):
        """
        托盘图标点击事件处理

        参数:
            reason: 点击原因
        """
        if reason == QSystemTrayIcon.Trigger:  # 左键单击
            self.show_normal()

    def show_normal(self):
        """从托盘恢复显示窗口"""
        self.setWindowFlags(
            Qt.FramelessWindowHint |
            Qt.WindowStaysOnTopHint |
            Qt.Tool |
            Qt.BypassWindowManagerHint |
            Qt.WindowTransparentForInput |
            Qt.ToolTip  # 保持不显示任务栏图标
        )
        self.show()
        self.activateWindow()

    def apply_windows_optimizations(self):
        """Windows平台专用优化"""
        try:
            import ctypes
            hwnd = self.winId().__int__()
            ctypes.windll.user32.SetWindowLongA(
                hwnd, -20,  # GWL_EXSTYLE
                0x80000 |  # WS_EX_LAYERED
                0x20 |  # WS_EX_TRANSPARENT
                0x00000020  # WS_EX_TOOLWINDOW
            )
        except Exception as e:
            print(f"Windows优化失败: {e}")

    def hide_from_taskbar(self):
        """Windows API方式彻底隐藏任务栏图标"""
        try:
            import ctypes
            hwnd = self.winId().__int__()
            ctypes.windll.user32.SetWindowLongA(
                hwnd, -20,  # GWL_EXSTYLE
                0x00000080 |  # WS_EX_TOOLWINDOW
                0x08000000 |  # WS_EX_NOACTIVATE
                0x00000020  # WS_EX_TRANSPARENT
            )
        except Exception as e:
            print(f"隐藏任务栏图标失败: {e}")

    def load_window_position(self):
        """从文件加载窗口位置信息"""
        pos_data = self.load_position()
        if pos_data:
            self.setGeometry(
                pos_data["x"],
                pos_data["y"],
                pos_data["width"],
                pos_data["height"]
            )
            if "visible" in pos_data:
                self.setVisible(pos_data["visible"])
        else:
            self.center_window()

    def center_window(self):
        """将窗口居中显示"""
        screen_geometry = QApplication.primaryScreen().geometry()
        screen_center = screen_geometry.center()
        self.move(
            screen_center.x() - self.width() // 2,
            screen_center.y() - self.height() // 2
        )
        self.save_position()

    def check_hide_condition(self):
        """检查自动隐藏条件"""
        if self.settings["auto_hide"]:
            if self.rect().contains(self.mapFromGlobal(QCursor.pos())):
                self.opacity = 1.0
                self.setWindowOpacity(self.opacity)
                return

            if self.opacity > 0.15:
                self.opacity -= 0.05
                self.setWindowOpacity(self.opacity)
            else:
                self.setWindowOpacity(0.15)
        else:
            self.setWindowOpacity(1.0)
    def paintEvent(self, event):
        """绘制准星"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing)

        center = self.rect().center()
        gap = self.settings["center_gap"]
        half_size = self.settings["size"] // 2

        # 设置准星和轮廓颜色的透明度
        opacity = self.settings["opacity"]
        color = QColor(self.settings["color"])
        color.setAlphaF(opacity)

        outline_color = QColor(self.settings["outline_color"])
        outline_color.setAlphaF(opacity)

        # 绘制轮廓（如果有）
        if self.settings["outline_enabled"] and self.settings["outline_width"] > 0:
            outline_pen = QPen(outline_color,
                               self.settings["outline_width"] + self.settings["line_width"])
            outline_pen.setCapStyle(Qt.RoundCap)
            painter.setPen(outline_pen)

            style = self.settings["style"]
            hide_cross = self.settings["hide_cross"]
            hide_center = self.settings["hide_center"]

            if style == 1 and not hide_cross:  # T字形样式
                painter.drawLine(center.x(), center.y() + half_size, center.x(), center.y() + gap)  # 下
                painter.drawLine(center.x() - half_size, center.y(), center.x() - gap, center.y())  # 左
                painter.drawLine(center.x() + half_size, center.y(), center.x() + gap, center.y())  # 右

                if not hide_center:
                    painter.drawEllipse(center,
                                        self.settings["center_radius"] + self.settings["outline_width"] / 2,
                                        self.settings["center_radius"] + self.settings["outline_width"] / 2)

            elif style == 2 and not hide_cross:  # 十字线样式
                painter.drawLine(center.x(), center.y() - half_size, center.x(), center.y() - gap)  # 上
                painter.drawLine(center.x(), center.y() + half_size, center.x(), center.y() + gap)  # 下
                painter.drawLine(center.x() - half_size, center.y(), center.x() - gap, center.y())  # 左
                painter.drawLine(center.x() + half_size, center.y(), center.x() + gap, center.y())  # 右

                if not hide_center:
                    painter.drawLine(center.x(), center.y() - 1, center.x(), center.y() + 1)  # 中心垂直线
                    painter.drawLine(center.x() - 1, center.y(), center.x() + 1, center.y())  # 中心水平线
                    painter.drawEllipse(center,
                                        self.settings["center_radius"] + self.settings["outline_width"] / 2,
                                        self.settings["center_radius"] + self.settings["outline_width"] / 2)

            elif style == 3 and not hide_cross:  # 圆环样式
                inner_radius = gap
                painter.setBrush(Qt.NoBrush)
                painter.drawEllipse(center, inner_radius, inner_radius)

                painter.drawLine(center.x() - inner_radius, center.y(), center.x() - gap, center.y())  # 左
                painter.drawLine(center.x() + inner_radius, center.y(), center.x() + gap, center.y())  # 右
                painter.drawLine(center.x(), center.y() - inner_radius, center.x(), center.y() - gap)  # 上
                painter.drawLine(center.x(), center.y() + inner_radius, center.x(), center.y() + gap)  # 下

                if not hide_center:
                    painter.drawEllipse(center,
                                        self.settings["center_radius"] + self.settings["outline_width"] / 2,
                                        self.settings["center_radius"] + self.settings["outline_width"] / 2)

            if hide_cross or style == 4:  # 仅中心点模式
                if not hide_center:
                    painter.drawEllipse(center,
                                        self.settings["center_radius"] + self.settings["outline_width"] / 2,
                                        self.settings["center_radius"] + self.settings["outline_width"] / 2)

        # 绘制准星主体
        painter.setPen(QPen(color, self.settings["line_width"]))
        painter.setBrush(color)

        style = self.settings["style"]
        hide_cross = self.settings["hide_cross"]
        hide_center = self.settings["hide_center"]

        if style == 1 and not hide_cross:  # T字形样式
            painter.drawLine(center.x(), center.y() + half_size, center.x(), center.y() + gap)  # 下
            painter.drawLine(center.x() - half_size, center.y(), center.x() - gap, center.y())  # 左
            painter.drawLine(center.x() + half_size, center.y(), center.x() + gap, center.y())  # 右

            if not hide_center:
                painter.drawEllipse(center, self.settings["center_radius"], self.settings["center_radius"])

        elif style == 2 and not hide_cross:  # 十字线样式
            painter.drawLine(center.x(), center.y() - half_size, center.x(), center.y() - gap)  # 上
            painter.drawLine(center.x(), center.y() + half_size, center.x(), center.y() + gap)  # 下
            painter.drawLine(center.x() - half_size, center.y(), center.x() - gap, center.y())  # 左
            painter.drawLine(center.x() + half_size, center.y(), center.x() + gap, center.y())  # 右

            if not hide_center:
                painter.drawLine(center.x(), center.y() - 1, center.x(), center.y() + 1)  # 中心垂直线
                painter.drawLine(center.x() - 1, center.y(), center.x() + 1, center.y())  # 中心水平线
                painter.setPen(Qt.NoPen)
                painter.drawEllipse(center, self.settings["center_radius"], self.settings["center_radius"])

        elif style == 3 and not hide_cross:  # 圆环样式
            inner_radius = gap
            painter.setPen(QPen(color, self.settings["line_width"]))
            painter.setBrush(Qt.NoBrush)
            painter.drawEllipse(center, inner_radius, inner_radius)

            painter.drawLine(center.x() - inner_radius, center.y(), center.x() - gap, center.y())  # 左
            painter.drawLine(center.x() + inner_radius, center.y(), center.x() + gap, center.y())  # 右
            painter.drawLine(center.x(), center.y() - inner_radius, center.x(), center.y() - gap)  # 上
            painter.drawLine(center.x(), center.y() + inner_radius, center.x(), center.y() + gap)  # 下

            if not hide_center:
                painter.setPen(Qt.NoPen)
                painter.setBrush(color)
                painter.drawEllipse(center, self.settings["center_radius"], self.settings["center_radius"])

        if hide_cross or style == 4:  # 仅中心点模式
            if not hide_center:
                painter.setPen(Qt.NoPen)
                painter.setBrush(color)
                painter.drawEllipse(center, self.settings["center_radius"], self.settings["center_radius"])

    def show_settings(self):
        """显示设置对话框"""
        if not self.isVisible():
            self.setVisible(True)

        try:
            settings_dialog = SettingsDialog(self.settings, parent=self)
            if settings_dialog.exec() == QDialog.Accepted:
                self.apply_settings(settings_dialog.get_settings())
        except Exception as e:
            print(f"设置对话框错误: {e}")

    def apply_settings(self, settings):
        """应用新设置"""
        self.settings = settings
        self.update()  # 重绘准星
        self.save_settings()  # 保存设置

    def save_settings(self):
        """保存设置到文件"""
        try:
            # 准备可序列化的设置数据
            save_data = self.settings.copy()
            # 转换QColor为可序列化格式
            save_data["color"] = {
                "red": self.settings["color"].red(),
                "green": self.settings["color"].green(),
                "blue": self.settings["color"].blue(),
                "alpha": self.settings["color"].alpha()
            }
            save_data["outline_color"] = {
                "red": self.settings["outline_color"].red(),
                "green": self.settings["outline_color"].green(),
                "blue": self.settings["outline_color"].blue(),
                "alpha": self.settings["outline_color"].alpha()
            }

            # 保存到文件
            with open(SETTINGS_FILE, "w") as f:
                json.dump(save_data, f, indent=4)
        except Exception as e:
            print(f"保存设置失败: {e}")

    def load_settings(self):
        """从文件加载设置"""
        default_settings = {
            "size": 60,
            "line_width": 2,
            "center_radius": 5,
            "center_gap": 15,
            "color": QColor(255, 50, 50, 230),
            "opacity": 1.0,
            "bg_opacity": 0,
            "style": 1,
            "show_hint": True,
            "auto_hide": False,
            "hide_cross": False,
            "hide_center": False,
            "outline_enabled": False,
            "outline_width": 1,
            "outline_color": QColor(0, 0, 0, 255),
        }

        try:
            if os.path.exists(SETTINGS_FILE):
                with open(SETTINGS_FILE, "r") as f:
                    loaded = json.load(f)

                # 确保加载的设置中有opacity值
                if "opacity" not in loaded:
                    loaded["opacity"] = default_settings["opacity"]
                if "bg_opacity" not in loaded:
                    loaded["bg_opacity"] = default_settings["bg_opacity"]

                # 还原QColor对象
                color_data = loaded.get("color", {})
                color = QColor(
                    color_data.get("red", 255),
                    color_data.get("green", 50),
                    color_data.get("blue", 50),
                    color_data.get("alpha", 230)
                )

                # 还原轮廓颜色
                outline_color_data = loaded.get("outline_color", {})
                outline_color = QColor(
                    outline_color_data.get("red", 0),
                    outline_color_data.get("green", 0),
                    outline_color_data.get("blue", 0),
                    outline_color_data.get("alpha", 255)
                )

                # 更新设置
                loaded["color"] = color
                loaded["outline_color"] = outline_color

                # 合并默认设置和加载的设置
                for key in default_settings:
                    if key not in loaded:
                        loaded[key] = default_settings[key]

                return loaded
        except Exception as e:
            print(f"加载设置失败: {e}")

        return default_settings

    def save_position(self):
        """保存窗口位置信息"""
        try:
            # 保存位置、大小和可见状态
            data = {
                "x": self.x(),
                "y": self.y(),
                "width": self.width(),
                "height": self.height(),
                "visible": self.isVisible()
            }

            with open(POSITION_FILE, "w") as f:
                json.dump(data, f, indent=4)
        except Exception as e:
            print(f"保存位置失败: {e}")

    def load_position(self):
        """加载窗口位置信息"""
        try:
            if os.path.exists(POSITION_FILE):
                with open(POSITION_FILE, "r") as f:
                    return json.load(f)
        except Exception as e:
            print(f"加载位置失败: {e}")

        return None

    def save_position_history(self):
        """保存位置历史记录"""
        try:
            with open(POSITION_HISTORY_FILE, "w") as f:
                json.dump(self.position_history, f, indent=4)
        except Exception as e:
            print(f"保存位置历史失败: {e}")

    def load_position_history(self):
        """加载位置历史记录"""
        try:
            if os.path.exists(POSITION_HISTORY_FILE):
                with open(POSITION_HISTORY_FILE, "r") as f:
                    return json.load(f)
        except Exception as e:
            print(f"加载位置历史失败: {e}")
        return []

    def quit_app(self):
        """退出应用程序"""
        self.save_position()
        QApplication.quit()

    def closeEvent(self, event):
        """窗口关闭事件处理"""
        self.quit_app()
        event.accept()


class SettingsDialog(QDialog):
    """
    准星设置对话框 - 完整实现
    包含位置控制、外观设置和关于页面
    """

    def __init__(self, settings, parent=None):
        super().__init__(parent)
        self.settings = settings.copy()
        self.preview_settings = settings.copy()
        self.parent_crosshair = parent
        self.original_position = parent.pos()
        self.temp_position = parent.pos()

        # 窗口设置
        self.setWindowTitle("准星设置")
        self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        self.setFixedSize(700, 700)

        # 创建主布局
        main_layout = QVBoxLayout()
        self.setLayout(main_layout)

        # 创建标签页
        self.tab_widget = QTabWidget()
        main_layout.addWidget(self.tab_widget)

        # 添加各设置页
        self.setup_position_tab()  # 位置控制页
        self.setup_appearance_tab()  # 外观设置页
        self.setup_about_tab()  # 关于页面

        # 添加底部按钮
        button_layout = QHBoxLayout()

        reset_all_btn = QPushButton("重置全部")
        reset_all_btn.clicked.connect(self.reset_defaults)
        button_layout.addWidget(reset_all_btn)

        button_layout.addStretch()

        reset_current_btn = QPushButton("重置当前页")
        reset_current_btn.clicked.connect(self.reset_current_tab)
        button_layout.addWidget(reset_current_btn)

        cancel_btn = QPushButton("取消")
        cancel_btn.clicked.connect(self.reject)
        button_layout.addWidget(cancel_btn)

        apply_btn = QPushButton("应用")
        apply_btn.clicked.connect(self.accept)
        button_layout.addWidget(apply_btn)

        exit_btn = QPushButton("退出程序")
        exit_btn.clicked.connect(self.exit_app)
        button_layout.addWidget(exit_btn)

        main_layout.addLayout(button_layout)

        # 初始化状态
        self.update_position_info()
        self.update_preview()
        self.load_position_history()

    def setup_position_tab(self):
        """位置控制页设置"""
        position_tab = QWidget()
        layout = QHBoxLayout()
        position_tab.setLayout(layout)

        # 左侧控制面板
        control_panel = QWidget()
        control_layout = QVBoxLayout()
        control_panel.setLayout(control_layout)
        layout.addWidget(control_panel, 1)

        # 当前位置信息
        self.position_info = QLabel()
        self.position_info.setAlignment(Qt.AlignCenter)
        control_layout.addWidget(self.position_info)

        # 步长设置
        step_layout = QHBoxLayout()
        step_layout.addWidget(QLabel("移动步长:"))

        self.step_spinner = QSpinBox()
        self.step_spinner.setRange(1, 50)
        self.step_spinner.setValue(5)
        step_layout.addWidget(self.step_spinner)

        control_layout.addLayout(step_layout)

        # 方向控制按钮
        button_size = QSize(50, 50)
        grid_layout = QGridLayout()
        grid_layout.setSpacing(10)

        up_btn = QPushButton("↑")
        up_btn.setFixedSize(button_size)
        up_btn.clicked.connect(lambda: self.move_crosshair(0, -self.step_spinner.value()))
        grid_layout.addWidget(up_btn, 0, 1)

        left_btn = QPushButton("←")
        left_btn.setFixedSize(button_size)
        left_btn.clicked.connect(lambda: self.move_crosshair(-self.step_spinner.value(), 0))
        grid_layout.addWidget(left_btn, 1, 0)

        center_btn = QPushButton("居中")
        center_btn.setFixedSize(button_size.width() * 1, button_size.height())
        center_btn.clicked.connect(self.center_crosshair)
        grid_layout.addWidget(center_btn, 1, 1)

        right_btn = QPushButton("→")
        right_btn.setFixedSize(button_size)
        right_btn.clicked.connect(lambda: self.move_crosshair(self.step_spinner.value(), 0))
        grid_layout.addWidget(right_btn, 1, 2)

        down_btn = QPushButton("↓")
        down_btn.setFixedSize(button_size)
        down_btn.clicked.connect(lambda: self.move_crosshair(0, self.step_spinner.value()))
        grid_layout.addWidget(down_btn, 2, 1)

        control_layout.addLayout(grid_layout)

        # 位置历史记录
        history_group = QGroupBox("位置记录")
        history_layout = QVBoxLayout()
        history_group.setLayout(history_layout)
        control_layout.addWidget(history_group)

        self.position_list = QListWidget()
        self.position_list.setMaximumHeight(100)
        history_layout.addWidget(self.position_list)

        btn_layout = QHBoxLayout()

        self.save_pos_btn = QPushButton("保存当前位置")
        self.save_pos_btn.clicked.connect(self.save_current_position)
        btn_layout.addWidget(self.save_pos_btn)

        self.apply_pos_btn = QPushButton("应用选中位置")
        self.apply_pos_btn.clicked.connect(self.apply_selected_position)
        btn_layout.addWidget(self.apply_pos_btn)

        self.delete_pos_btn = QPushButton("删除选中记录")
        self.delete_pos_btn.clicked.connect(self.delete_selected_position)
        btn_layout.addWidget(self.delete_pos_btn)

        history_layout.addLayout(btn_layout)

        # 右侧预览面板
        preview_group = QGroupBox("位置预览")
        preview_layout = QVBoxLayout()
        preview_group.setLayout(preview_layout)
        layout.addWidget(preview_group, 2)

        self.screen_preview = QLabel()
        self.screen_preview.setAlignment(Qt.AlignCenter)
        self.screen_preview.setMinimumSize(300, 300)
        self.screen_preview.setStyleSheet("background-color: black; border: 1px solid #555;")
        preview_layout.addWidget(self.screen_preview)

        self.tab_widget.addTab(position_tab, "位置控制")

    def setup_appearance_tab(self):
        """外观设置页"""
        appearance_tab = QWidget()
        layout = QVBoxLayout()
        appearance_tab.setLayout(layout)

        # 准星样式
        style_layout = QHBoxLayout()
        style_layout.addWidget(QLabel("样式:"))

        self.style_combo = QComboBox()
        self.style_combo.addItems(["T字形", "十字线", "圆环", "仅中心点"])
        self.style_combo.setCurrentIndex(self.settings["style"] - 1)
        self.style_combo.currentIndexChanged.connect(self.update_center_point_options)
        self.style_combo.currentIndexChanged.connect(self.update_preview)
        style_layout.addWidget(self.style_combo)

        style_layout.addStretch()
        layout.addLayout(style_layout)

        # 颜色设置
        color_layout = QHBoxLayout()
        color_layout.addWidget(QLabel("准星颜色:"))

        self.color_btn = QPushButton()
        self.color_btn.setFixedSize(70, 30)
        self.update_color_button(self.color_btn, self.settings["color"])
        self.color_btn.clicked.connect(lambda: self.select_color(self.color_btn))
        color_layout.addWidget(self.color_btn)

        color_layout.addStretch()
        layout.addLayout(color_layout)

        # 尺寸设置
        self.size_slider = self.create_slider_control("十字线长度:", 10, 250, self.settings["size"], layout)
        self.size_slider.valueChanged.connect(self.update_preview)

        # 隐藏选项
        self.hide_cross_cb = QCheckBox("隐藏辅助线（比如十字线，圆环等等，仅保留中心点）")
        self.hide_cross_cb.setChecked(self.settings["hide_cross"])
        self.hide_cross_cb.stateChanged.connect(self.update_preview)
        layout.addWidget(self.hide_cross_cb)

        self.hide_center_cb = QCheckBox("隐藏中心点")
        self.hide_center_cb.setChecked(self.settings["hide_center"])
        self.hide_center_cb.stateChanged.connect(self.update_preview)
        layout.addWidget(self.hide_center_cb)

        # 线条设置
        self.line_spinner = self.create_spinner_control("线宽:", 1, 10, self.settings["line_width"], layout)
        self.line_spinner.valueChanged.connect(self.update_preview)

        self.gap_spinner = self.create_spinner_control("中心间隙:", 5, 50, self.settings["center_gap"], layout)
        self.gap_spinner.valueChanged.connect(self.update_preview)

        self.center_spinner = self.create_spinner_control("中心点半径:", 1, 30, self.settings["center_radius"], layout)
        self.center_spinner.valueChanged.connect(self.update_preview)

        # 透明度设置
        self.bg_slider = self.create_slider_control("准星不透明度:", 0, 100, self.settings["opacity"] * 100, layout)
        self.bg_slider.valueChanged.connect(self.update_preview)

        # 轮廓设置
        self.outline_enabled_cb = QCheckBox("启用轮廓")
        self.outline_enabled_cb.setChecked(self.settings["outline_enabled"])
        self.outline_enabled_cb.stateChanged.connect(self.update_preview)
        layout.addWidget(self.outline_enabled_cb)

        self.outline_width_spinner = self.create_spinner_control("轮廓宽度:", 1, 5, self.settings["outline_width"],
                                                                 layout)
        self.outline_width_spinner.valueChanged.connect(self.update_preview)

        outline_color_layout = QHBoxLayout()
        outline_color_layout.addWidget(QLabel("轮廓颜色:"))

        self.outline_color_btn = QPushButton()
        self.outline_color_btn.setFixedSize(70, 30)
        self.update_color_button(self.outline_color_btn, self.settings["outline_color"])
        self.outline_color_btn.clicked.connect(lambda: self.select_color(self.outline_color_btn, is_outline=True))
        outline_color_layout.addWidget(self.outline_color_btn)

        outline_color_layout.addStretch()
        layout.addLayout(outline_color_layout)

        # 自动隐藏功能（从高级设置移过来）
        self.auto_hide_cb = QCheckBox("鼠标离开时自动隐藏")
        self.auto_hide_cb.setChecked(self.settings["auto_hide"])
        layout.addWidget(self.auto_hide_cb)

        # 预览区域
        preview_layout = QHBoxLayout()
        preview_layout.addWidget(QLabel("样式预览:"))

        self.preview_widget = QWidget()
        self.preview_widget.setFixedSize(150, 150)
        self.preview_widget.setStyleSheet("background-color: rgba(100, 100, 100, 150);")
        preview_layout.addWidget(self.preview_widget)
        preview_layout.addStretch()

        layout.addLayout(preview_layout)

        # 重写预览窗口的绘制方法
        self.preview_widget.paintEvent = self.paint_preview

        self.tab_widget.addTab(appearance_tab, "外观设置")

    def setup_about_tab(self):
        """关于页面设置"""
        about_tab = QWidget()
        layout = QVBoxLayout(about_tab)
        layout.setContentsMargins(0, 0, 0, 0)

        scroll_area = QScrollArea()
        scroll_area.setWidgetResizable(True)
        scroll_area.setFrameShape(QFrame.NoFrame)
        scroll_area.setStyleSheet("""
            QScrollArea { background: transparent; border: none; }
            QScrollBar:vertical { width: 10px; background: rgba(200,200,200,100); }
            QScrollBar::handle:vertical { 
                background: rgba(150,150,150,150); 
                min-height: 30px; 
                border-radius: 5px; 
            }
        """)

        content = QWidget()
        content_layout = QVBoxLayout(content)
        content_layout.setContentsMargins(25, 25, 25, 25)
        content_layout.setSpacing(15)

        # 程序图标
        icon_label = QLabel()
        pixmap = self.create_program_icon(60)
        icon_label.setPixmap(pixmap)
        icon_label.setAlignment(Qt.AlignCenter)
        content_layout.addWidget(icon_label, 0, Qt.AlignCenter)

        # 程序名称
        title_label = QLabel("准星工具")
        title_label.setStyleSheet("""
            font-size: 24px;
            font-weight: bold;
            color: #3498db;
            margin-bottom: 5px;
        """)
        title_label.setAlignment(Qt.AlignCenter)
        content_layout.addWidget(title_label)

        # 版本信息
        version_label = QLabel("v1.0.0_Alpha_1 | 编译日期：2025-07-21")
        version_label.setStyleSheet("font-size: 13px; color: #666;")
        version_label.setAlignment(Qt.AlignCenter)
        content_layout.addWidget(version_label)

        # 关于文本
        about_text = QLabel("""
        <div style="line-height: 1.7; font-size: 14px;">
            <h3 style="color: #3498db; margin-top: 5px; margin-bottom: 10px;">关于本程序</h3>
            <p style="margin-bottom: 15px;">
            这是一款专为FPS游戏玩家设计的准星覆盖工具，采用先进的渲染技术确保在游戏中稳定显示。
            完全通过代码生成界面元素，无需任何外部资源文件。
            <p style="margin-bottom: 15px;">比如一个用途：如果你是一位CS2的野牛玩家，用的是牛吃草的准星，没有中心点，且显示器不自带准星功能又或者自带的准星不满足需求，那么这款软件刚好适合你，让你在使用牛吃草准星时还能保留中心点</p>
            </p>

            <h3 style="color: #3498db; margin-top: 15px; margin-bottom: 10px;">主要功能</h3>
            <ul style="margin-left: 5px; margin-bottom: 15px;">
                <li style="margin-bottom: 8px;">多种准星样式选择</li>
                <li style="margin-bottom: 8px;">自定义颜色和大小</li>
                <li style="margin-bottom: 8px;">位置记忆功能</li>
                <li style="margin-bottom: 8px;">低资源占用</li>
            </ul>

            <h3 style="color: #3498db; margin-top: 15px; margin-bottom: 10px;">使用方法</h3>
            <ol style="margin-left: 5px; margin-bottom: 15px;">
                <li style="margin-bottom: 8px;">通过系统托盘图标访问设置</li>
                <li style="margin-bottom: 8px;">在位置控制页调整准星位置</li>
                <li style="margin-bottom: 8px;">在外观设置页自定义准星样式</li>
            </ol>
        </div>
        """)
        about_text.setWordWrap(True)
        about_text.setTextFormat(Qt.RichText)
        content_layout.addWidget(about_text)

        # 页脚
        footer = QLabel("""
        <div style="text-align: center; margin-top: 20px; font-size: 13px;">
            <p style="color: #888; margin-bottom: 5px;">开发者: JQ邢道荣</p>
            <p>
                <a href="https://gitee.com/lrror404/fps-crosshair-tool" 
                   style="color: #3498db; text-decoration: none; margin: 0 10px;">项目主页</a>
                <span style="color: #ccc;">|</span>
                <a href="liegnaioo7@gmail.com" 
                   style="color: #3498db; text-decoration: none; margin: 0 10px;">联系作者</a>
            </p>
        </div>
        """)
        footer.setOpenExternalLinks(True)
        content_layout.addWidget(footer)

        content_layout.addStretch()

        scroll_area.setWidget(content)
        layout.addWidget(scroll_area)

        self.tab_widget.addTab(about_tab, "关于")

    def create_slider_control(self, label, min_val, max_val, current_val, parent_layout):
        """创建滑块控件"""
        layout = QHBoxLayout()

        label_widget = QLabel(label)
        layout.addWidget(label_widget)

        value_label = QLabel(str(current_val))
        value_label.setFixedWidth(40)
        layout.addWidget(value_label)

        slider = QSlider(Qt.Horizontal)
        slider.setRange(min_val, max_val)
        slider.setValue(current_val)
        slider.setFixedWidth(150)
        slider.valueChanged.connect(lambda v: value_label.setText(str(v)))
        layout.addWidget(slider)

        layout.addStretch()
        parent_layout.addLayout(layout)

        return slider

    def create_spinner_control(self, label, min_val, max_val, current_val, parent_layout):
        """创建微调框控件"""
        layout = QHBoxLayout()

        label_widget = QLabel(label)
        layout.addWidget(label_widget)

        spinner = QSpinBox()
        spinner.setRange(min_val, max_val)
        spinner.setValue(current_val)
        layout.addWidget(spinner)

        layout.addStretch()
        parent_layout.addLayout(layout)

        return spinner

    def update_color_button(self, button, color):
        """更新颜色按钮显示"""
        pixmap = QPixmap(button.size())
        pixmap.fill(Qt.transparent)

        painter = QPainter(pixmap)
        painter.setBrush(QBrush(color))
        painter.setPen(Qt.NoPen)
        painter.drawRect(pixmap.rect())
        painter.end()

        button.setIcon(QIcon(pixmap))
        button.setStyleSheet(f"""
            QPushButton {{
                border: 1px solid #888;
                border-radius: 4px;
                background-color: rgba({color.red()}, {color.green()}, {color.blue()}, {color.alpha()});
            }}
        """)

    def create_program_icon(self, size):
        """创建程序图标"""
        pixmap = QPixmap(size, size)
        pixmap.fill(Qt.transparent)

        painter = QPainter(pixmap)
        painter.setRenderHint(QPainter.Antialiasing)

        gradient = QConicalGradient(size / 2, size / 2, 0)
        gradient.setColorAt(0, QColor(52, 152, 219, 180))
        gradient.setColorAt(1, QColor(155, 89, 182, 180))
        painter.setBrush(gradient)
        painter.setPen(Qt.NoPen)
        painter.drawEllipse(5, 5, size - 10, size - 10)

        center = size / 2
        arm_length = size * 0.35
        painter.setPen(QPen(Qt.white, size * 0.08, Qt.SolidLine, Qt.RoundCap))
        painter.drawLine(center - arm_length, center, center + arm_length, center)
        painter.drawLine(center, center - arm_length, center, center + arm_length)

        painter.setPen(Qt.NoPen)
        painter.setBrush(Qt.white)
        painter.drawEllipse(QPointF(center, center), size * 0.05, size * 0.05)

        painter.end()
        return pixmap

    def update_position_info(self):
        """更新位置信息显示"""
        screen = QApplication.primaryScreen()
        resolution = f"{screen.size().width()}x{screen.size().height()}"
        pos = self.parent_crosshair.pos()
        center = self.parent_crosshair.rect().center()
        global_center = self.parent_crosshair.mapToGlobal(center)

        self.position_info.setText(
            f"当前分辨率: {resolution}\n"
            f"窗口位置: ({pos.x()}, {pos.y()})\n"
            f"准星中心: ({global_center.x()}, {global_center.y()})"
        )

    def move_crosshair(self, dx, dy):
        """移动准星位置"""
        current_pos = self.parent_crosshair.pos()
        new_pos = QPoint(current_pos.x() + dx, current_pos.y() + dy)
        self.parent_crosshair.move(new_pos)
        self.temp_position = new_pos
        self.update_position_info()
        self.update_screen_preview()

    def center_crosshair(self):
        """居中准星"""
        screen_geometry = QApplication.primaryScreen().geometry()
        screen_center = screen_geometry.center()
        new_pos = QPoint(
            screen_center.x() - self.parent_crosshair.width() // 2,
            screen_center.y() - self.parent_crosshair.height() // 2
        )
        self.parent_crosshair.move(new_pos)
        self.temp_position = new_pos
        self.update_position_info()
        self.update_screen_preview()

    def update_screen_preview(self):
        """更新屏幕预览"""
        try:
            screen = QApplication.primaryScreen()
            if not screen:
                return

            crosshair_rect = self.parent_crosshair.geometry()
            preview_width = self.screen_preview.width()
            preview_height = self.screen_preview.height()

            x = crosshair_rect.center().x() - preview_width // 2
            y = crosshair_rect.center().y() - preview_height // 2

            screen_rect = screen.geometry()
            x = max(screen_rect.left(), min(x, screen_rect.right() - preview_width))
            y = max(screen_rect.top(), min(y, screen_rect.bottom() - preview_height))

            screenshot = screen.grabWindow(0, x, y, preview_width, preview_height)

            # 绘制准星
            painter = QPainter(screenshot)
            painter.setRenderHint(QPainter.Antialiasing)

            center = screenshot.rect().center()
            settings = self.parent_crosshair.settings
            gap = settings["center_gap"]
            half_size = settings["size"] // 2
            opacity = settings["opacity"]
            color = QColor(settings["color"])
            color.setAlphaF(opacity)
            outline_color = QColor(settings["outline_color"])
            outline_color.setAlphaF(opacity)

            # 绘制轮廓
            if settings["outline_enabled"] and settings["outline_width"] > 0:
                outline_pen = QPen(outline_color,
                                   settings["outline_width"] + settings["line_width"])
                outline_pen.setCapStyle(Qt.RoundCap)
                painter.setPen(outline_pen)

                # 根据样式绘制轮廓
                self.draw_crosshair(painter, center, half_size, gap, settings, outline=True)

            # 绘制准星主体
            painter.setPen(QPen(color, settings["line_width"]))
            painter.setBrush(color)
            self.draw_crosshair(painter, center, half_size, gap, settings)

            painter.end()

            self.screen_preview.setPixmap(screenshot.scaled(
                self.screen_preview.size(),
                Qt.KeepAspectRatioByExpanding,
                Qt.SmoothTransformation
            ))

        except Exception as e:
            print(f"更新屏幕预览失败: {e}")

    def draw_crosshair(self, painter, center, half_size, gap, settings, outline=False):
        """绘制准星"""
        style = settings["style"]
        hide_cross = settings["hide_cross"]
        hide_center = settings["hide_center"]
        radius = settings["center_radius"]

        if outline:
            radius += settings["outline_width"] / 2

        if style == 1 and not hide_cross:  # T字形
            painter.drawLine(center.x(), center.y() + half_size, center.x(), center.y() + gap)
            painter.drawLine(center.x() - half_size, center.y(), center.x() - gap, center.y())
            painter.drawLine(center.x() + half_size, center.y(), center.x() + gap, center.y())

            if not hide_center and not outline:
                painter.drawEllipse(center, radius, radius)

        elif style == 2 and not hide_cross:  # 十字线
            painter.drawLine(center.x(), center.y() - half_size, center.x(), center.y() - gap)
            painter.drawLine(center.x(), center.y() + half_size, center.x(), center.y() + gap)
            painter.drawLine(center.x() - half_size, center.y(), center.x() - gap, center.y())
            painter.drawLine(center.x() + half_size, center.y(), center.x() + gap, center.y())

            if not hide_center and not outline:
                painter.drawLine(center.x(), center.y() - 1, center.x(), center.y() + 1)
                painter.drawLine(center.x() - 1, center.y(), center.x() + 1, center.y())
                painter.drawEllipse(center, radius, radius)

        elif style == 3 and not hide_cross:  # 圆环
            inner_radius = gap
            painter.drawEllipse(center, inner_radius, inner_radius)
            painter.drawLine(center.x() - inner_radius, center.y(), center.x() - gap, center.y())
            painter.drawLine(center.x() + inner_radius, center.y(), center.x() + gap, center.y())
            painter.drawLine(center.x(), center.y() - inner_radius, center.x(), center.y() - gap)
            painter.drawLine(center.x(), center.y() + inner_radius, center.x(), center.y() + gap)

            if not hide_center and not outline:
                painter.drawEllipse(center, radius, radius)

        if (hide_cross or style == 4) and not hide_center and not outline:  # 仅中心点
            painter.drawEllipse(center, radius, radius)

    def load_position_history(self):
        """加载位置历史记录"""
        self.position_list.clear()
        if hasattr(self.parent_crosshair, 'position_history'):
            for item in self.parent_crosshair.position_history:
                self.position_list.addItem(item['name'])

    def save_current_position(self):
        """保存当前位置"""
        screen = QApplication.primaryScreen()
        resolution = f"{screen.size().width()}x{screen.size().height()}"
        pos = self.parent_crosshair.pos()
        center = self.parent_crosshair.rect().center()
        global_center = self.parent_crosshair.mapToGlobal(center)

        name = f"{resolution} - ({global_center.x()}, {global_center.y()})"
        position_data = {
            'name': name,
            'x': pos.x(),
            'y': pos.y(),
            'resolution': resolution,
            'center_x': global_center.x(),
            'center_y': global_center.y()
        }

        self.parent_crosshair.position_history.append(position_data)
        self.parent_crosshair.save_position_history()
        self.load_position_history()

    def apply_selected_position(self):
        """应用选中的位置"""
        selected_items = self.position_list.selectedItems()
        if not selected_items:
            QMessageBox.warning(self, "警告", "请先选择一个位置记录")
            return

        selected_name = selected_items[0].text()
        for item in self.parent_crosshair.position_history:
            if item['name'] == selected_name:
                self.parent_crosshair.move(item['x'], item['y'])
                self.temp_position = QPoint(item['x'], item['y'])
                self.update_position_info()
                self.update_screen_preview()
                break

    def delete_selected_position(self):
        """删除选中的位置"""
        selected_items = self.position_list.selectedItems()
        if not selected_items:
            QMessageBox.warning(self, "警告", "请先选择一个位置记录")
            return

        selected_name = selected_items[0].text()
        for i, item in enumerate(self.parent_crosshair.position_history):
            if item['name'] == selected_name:
                del self.parent_crosshair.position_history[i]
                self.parent_crosshair.save_position_history()
                self.load_position_history()
                break

    def select_color(self, button, is_outline=False):
        """选择颜色"""
        if is_outline:
            current_color = self.settings["outline_color"]
        else:
            current_color = self.settings["color"]

        color = QColorDialog.getColor(current_color, self, "选择颜色")
        if color.isValid():
            if is_outline:
                self.settings["outline_color"] = color
                self.update_color_button(button, color)
            else:
                self.settings["color"] = color
                self.update_color_button(button, color)
            self.update_preview()

    def update_preview(self):
        """更新预览"""
        self.preview_settings = {
            "size": self.size_slider.value(),
            "line_width": self.line_spinner.value(),
            "center_radius": self.center_spinner.value(),
            "center_gap": self.gap_spinner.value(),
            "color": QColor(self.settings["color"]),
            "opacity": self.bg_slider.value() / 100,
            "style": self.style_combo.currentIndex() + 1,
            "hide_cross": self.hide_cross_cb.isChecked(),
            "hide_center": self.hide_center_cb.isChecked(),
            "outline_enabled": self.outline_enabled_cb.isChecked(),
            "outline_width": self.outline_width_spinner.value(),
            "outline_color": QColor(self.settings["outline_color"]),
        }

        self.preview_settings["color"].setAlphaF(self.preview_settings["opacity"])
        self.preview_settings["outline_color"].setAlphaF(self.preview_settings["opacity"])

        self.preview_widget.update()

    def paint_preview(self, event):
        """绘制预览"""
        if not hasattr(self, 'preview_settings'):
            return

        painter = QPainter(self.preview_widget)
        painter.setRenderHint(QPainter.Antialiasing)

        # 清除背景
        painter.fillRect(self.preview_widget.rect(), QColor(100, 100, 100, 150))

        center = self.preview_widget.rect().center()
        gap = self.preview_settings["center_gap"]
        half_size = max(10, self.preview_settings["size"] // 3)

        # 绘制轮廓
        if self.preview_settings["outline_enabled"] and self.preview_settings["outline_width"] > 0:
            outline_pen = QPen(
                self.preview_settings["outline_color"],
                self.preview_settings["outline_width"] + self.preview_settings["line_width"]
            )
            outline_pen.setCapStyle(Qt.RoundCap)
            painter.setPen(outline_pen)

            # 根据样式绘制轮廓
            self.draw_preview_crosshair(painter, center, half_size, gap, outline=True)

        # 绘制准星主体
        painter.setPen(QPen(self.preview_settings["color"], self.preview_settings["line_width"]))
        painter.setBrush(self.preview_settings["color"])
        self.draw_preview_crosshair(painter, center, half_size, gap)

    def draw_preview_crosshair(self, painter, center, half_size, gap, outline=False):
        """绘制预览准星"""
        style = self.preview_settings["style"]
        hide_cross = self.preview_settings["hide_cross"]
        hide_center = self.preview_settings["hide_center"]
        radius = self.preview_settings["center_radius"]

        if outline:
            radius += self.preview_settings["outline_width"] / 2

        if style == 1 and not hide_cross:  # T字形
            painter.drawLine(center.x(), center.y() + half_size, center.x(), center.y() + gap // 1.5)
            painter.drawLine(center.x() - half_size, center.y(), center.x() - gap // 1.5, center.y())
            painter.drawLine(center.x() + half_size, center.y(), center.x() + gap // 1.5, center.y())

            if not hide_center:
                painter.drawEllipse(center, radius, radius)

        elif style == 2 and not hide_cross:  # 十字线
            painter.drawLine(center.x(), center.y() - half_size, center.x(), center.y() - gap // 1.5)
            painter.drawLine(center.x(), center.y() + half_size, center.x(), center.y() + gap // 1.5)
            painter.drawLine(center.x() - half_size, center.y(), center.x() - gap // 1.5, center.y())
            painter.drawLine(center.x() + half_size, center.y(), center.x() + gap // 1.5, center.y())

            if not hide_center:
                if not outline:
                    painter.drawLine(center.x(), center.y() - 1, center.x(), center.y() + 1)
                    painter.drawLine(center.x() - 1, center.y(), center.x() + 1, center.y())
                painter.drawEllipse(center, radius, radius)

        elif style == 3 and not hide_cross:  # 圆环
            inner_radius = gap // 1.5
            painter.drawEllipse(center, inner_radius, inner_radius)
            painter.drawLine(center.x() - inner_radius, center.y(), center.x() - gap // 1.5, center.y())
            painter.drawLine(center.x() + inner_radius, center.y(), center.x() + gap // 1.5, center.y())
            painter.drawLine(center.x(), center.y() - inner_radius, center.x(), center.y() - gap // 1.5)
            painter.drawLine(center.x(), center.y() + inner_radius, center.x(), center.y() + gap // 1.5)

            if not hide_center:
                painter.drawEllipse(center, radius, radius)

        if (hide_cross or style == 4) and not hide_center:  # 仅中心点
            painter.drawEllipse(center, radius, radius)

    def update_center_point_options(self, index):
        """更新中心点选项状态"""
        is_center_only_style = (index == 3)  # "仅中心点"样式

        if is_center_only_style:
            self.hide_cross_cb.setChecked(False)
            self.hide_cross_cb.setEnabled(False)
            self.hide_center_cb.setChecked(False)
            self.hide_center_cb.setEnabled(False)
            self.hide_cross_cb.setStyleSheet("color: gray;")
            self.hide_center_cb.setStyleSheet("color: gray;")
        else:
            self.hide_cross_cb.setEnabled(True)
            self.hide_center_cb.setEnabled(True)
            self.hide_cross_cb.setStyleSheet("")
            self.hide_center_cb.setStyleSheet("")

        self.update_preview()

    def reset_current_tab(self):
        """重置当前标签页"""
        current_index = self.tab_widget.currentIndex()

        if current_index == 0:  # 位置控制页
            self.step_spinner.setValue(5)
        elif current_index == 1:  # 外观设置页
            self.line_spinner.setValue(2)
            self.gap_spinner.setValue(15)
            self.center_spinner.setValue(5)
            self.bg_slider.setValue(100)
            self.settings["color"] = QColor(255, 50, 50, 230)
            self.update_color_button(self.color_btn, self.settings["color"])

            self.outline_enabled_cb.setChecked(False)
            self.outline_width_spinner.setValue(1)
            self.settings["outline_color"] = QColor(0, 0, 0, 255)
            self.update_color_button(self.outline_color_btn, self.settings["outline_color"])

            self.auto_hide_cb.setChecked(False)

        self.update_center_point_options(self.style_combo.currentIndex())
        self.update_preview()

    def reset_defaults(self):
        """重置所有设置为默认值"""
        self.settings = {
            "size": 60,
            "line_width": 2,
            "center_radius": 5,
            "center_gap": 15,
            "color": QColor(255, 50, 50, 230),
            "opacity": 1.0,
            "bg_opacity": 0,
            "style": 1,
            "show_hint": True,
            "auto_hide": False,
            "hide_cross": False,
            "hide_center": False,
            "outline_enabled": False,
            "outline_width": 1,
            "outline_color": QColor(0, 0, 0, 255),
        }

        # 更新UI控件
        self.size_slider.setValue(self.settings["size"])
        self.style_combo.setCurrentIndex(self.settings["style"] - 1)
        self.line_spinner.setValue(self.settings["line_width"])
        self.gap_spinner.setValue(self.settings["center_gap"])
        self.center_spinner.setValue(self.settings["center_radius"])
        self.bg_slider.setValue(self.settings["opacity"] * 100)
        self.auto_hide_cb.setChecked(self.settings["auto_hide"])
        self.hide_cross_cb.setChecked(self.settings["hide_cross"])
        self.hide_center_cb.setChecked(self.settings["hide_center"])
        self.outline_enabled_cb.setChecked(self.settings["outline_enabled"])
        self.outline_width_spinner.setValue(self.settings["outline_width"])

        # 更新颜色按钮
        self.update_color_button(self.color_btn, self.settings["color"])
        self.update_color_button(self.outline_color_btn, self.settings["outline_color"])

        self.update_center_point_options(self.style_combo.currentIndex())
        self.update_preview()

    def get_settings(self):
        """获取当前设置"""
        return {
            "size": self.size_slider.value(),
            "line_width": self.line_spinner.value(),
            "center_radius": self.center_spinner.value(),
            "center_gap": self.gap_spinner.value(),
            "color": self.settings["color"],
            "opacity": self.bg_slider.value() / 100,
            "bg_opacity": 0,
            "style": self.style_combo.currentIndex() + 1,
            "show_hint": True,
            "auto_hide": self.auto_hide_cb.isChecked(),
            "hide_cross": False if (self.style_combo.currentIndex() == 3) else self.hide_cross_cb.isChecked(),
            "hide_center": False if (self.style_combo.currentIndex() == 3) else self.hide_center_cb.isChecked(),
            "outline_enabled": self.outline_enabled_cb.isChecked(),
            "outline_width": self.outline_width_spinner.value(),
            "outline_color": self.settings["outline_color"],
        }

    def accept(self):
        """应用设置并保存位置"""
        self.parent_crosshair.save_position()
        super().accept()

    def reject(self):
        """取消设置并恢复原始位置"""
        self.parent_crosshair.move(self.original_position)
        super().reject()

    def exit_app(self):
        """退出应用程序"""
        self.reject()
        QApplication.quit()


if __name__ == "__main__":

    app = QApplication(sys.argv)
    app.setStyle("Fusion")

    # 设置应用程序图标
    app_icon = QIcon(create_app_icon())
    app.setWindowIcon(app_icon)

    dark_palette = QPalette()
    dark_palette.setColor(QPalette.Window, QColor(53, 53, 53))
    dark_palette.setColor(QPalette.WindowText, Qt.white)
    dark_palette.setColor(QPalette.Base, QColor(25, 25, 25))
    dark_palette.setColor(QPalette.AlternateBase, QColor(53, 53, 53))
    dark_palette.setColor(QPalette.ToolTipBase, Qt.white)
    dark_palette.setColor(QPalette.ToolTipText, Qt.white)
    dark_palette.setColor(QPalette.Text, Qt.white)
    dark_palette.setColor(QPalette.Button, QColor(53, 53, 53))
    dark_palette.setColor(QPalette.ButtonText, Qt.white)
    dark_palette.setColor(QPalette.BrightText, Qt.red)
    dark_palette.setColor(QPalette.Link, QColor(42, 130, 218))
    dark_palette.setColor(QPalette.Highlight, QColor(42, 130, 218))
    dark_palette.setColor(QPalette.HighlightedText, Qt.black)
    app.setPalette(dark_palette)

    app.setQuitOnLastWindowClosed(False)

    crosshair = CrosshairWidget()
    crosshair.show()

    QTimer.singleShot(500, crosshair.show_settings)

    sys.exit(app.exec())